/*****************************************************************************
 *   Copyright (C) 2008 John Schember <john@nachtimwald.com>                 *
 *                                                                           *
 *   This file is part of niwbillmanager.                                    *
 *                                                                           *
 *   niwbillmanager is free software: you can redistribute it and/or         *
 *   modify it under the terms of the GNU General Public License as          *
 *   published by the Free Software Foundation, either version 3 of the      *
 *   License, or (at your option) any later version.                         *
 *                                                                           *
 *   niwbillmanager is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of          *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the            *
 *   GNU General Public License for more details.                            *
 *                                                                           *
 *   You should have received a copy of the GNU General Public License       *
 *   along with niwbillmanager. If not, see                                  *
 *   <http://www.gnu.org/licenses/>.                                         *
 *****************************************************************************/

#include <QBrush>
#include <QDialog>
#include <QFileDialog>
#include <QHeaderView>
#include <QInputDialog>
#include <QLocale>
#include <QMessageBox>
#include <QSettings>
#include <QStringList>

#include "../../constants.h"

#include "mainwindow.h"
#include "aboutdialog.h"
#include "billitemdialog.h"
#include "pluginbrowserdialog.h"
#include "remotelocationdialog.h"
#include "settingsdialog.h"

MainWindow::MainWindow()
{
    setupUi(this);
    filterList->setColumnHidden(0, true);
    itemList->setColumnHidden(0, true);
    tagList->setColumnHidden(0, true);

    m_lib = new NiwBillManager();
    m_pluginManager = new PluginManager(this, m_lib);
    m_settingsManager = new SettingsManager();

    loadSettings();
    clearCollectionInformation();
    filterList->topLevelItem(0)->setSelected(true);

    connectSignals();

    emit titleUpdate();
    emit undoRedoUpdate();
    actionEdit_Item->setEnabled(false);
    actionDelete_Item->setEnabled(false);
}

MainWindow::~MainWindow()
{
    delete m_lib;
    delete m_pluginManager;
    delete m_settingsManager;
}

QMenu *MainWindow::getToolsMenu()
{
    return menuTools;
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (checkSaveAndShouldContinueAction()) {
        saveSettings();
        event->accept();
    }
    else {
        event->ignore();
    }
}

QMenu *MainWindow::createPopupMenu()
{
    QMenu *menu = QMainWindow::createPopupMenu();

    menu->clear();
    menu->addAction(actionToolbar);
    menu->addAction(actionText_On_Toolbar);

    return menu;
}

void MainWindow::on_actionNew_triggered()
{
    if (checkSaveAndShouldContinueAction()) {
        m_lib->newCollection();

        clearCollectionInformation();

        emit uiUpdate();
    }
}

void MainWindow::on_actionOpen_triggered()
{
    if (!checkSaveAndShouldContinueAction()) {
        return;
    }

    bool open = false;
    QString oldCollectionLocation = m_collectionLocation;

    if (m_lib->isBackendRemote()) {
        RemoteLocationDialog remoteLocationDialog(this);

        remoteLocationDialog.exec();
        if (remoteLocationDialog.result() == QDialog::Accepted) {
            m_collectionLocation = remoteLocationDialog.getLocation();
            m_collectionUsername = remoteLocationDialog.getUsername();
            m_collectionLoginname = remoteLocationDialog.getLoginname();
            m_collectionPassword =remoteLocationDialog.getPassword();
            open = true;
        }
    }
    else {
        m_collectionLocation = QFileDialog::getOpenFileName(this,
            tr("Open Collection"), "", tr("Bill Collection")
            + " (*." + m_lib->getBackendFileExtenstion() + ")");
        if (m_collectionLocation != "") {
            open = true;
        }
    }

    if (open) {
        if (!m_lib->loadCollection(m_collectionLocation,
            m_collectionUsername, m_collectionLoginname, m_collectionPassword))
        {
            QMessageBox::critical(this, tr("Error Opening"),
                m_lib->getLastErrorMessage());
            m_collectionLocation = oldCollectionLocation;
        }
        emit uiUpdate();
    }
}

void MainWindow::on_actionSave_triggered()
{
    // Check if there is a location to save to.
    if (m_collectionLocation == "") {
        on_actionSave_As_triggered();
    }
    else {
        save();
    }
}

void MainWindow::on_actionSave_As_triggered()
{
    if (m_lib->isBackendRemote()) {
        RemoteLocationDialog remoteLocationDialog(this);

        remoteLocationDialog.exec();
        if (remoteLocationDialog.result() == QDialog::Accepted) {
            m_collectionLocation = remoteLocationDialog.getLocation();
            m_collectionUsername = remoteLocationDialog.getUsername();
            m_collectionLoginname = remoteLocationDialog.getLoginname();
            m_collectionPassword = remoteLocationDialog.getPassword();
        }
    }
    else {
        m_collectionLocation = QFileDialog::getSaveFileName(this,
            tr("Save Collection"), tr("untitled") + "."
            + m_lib->getBackendFileExtenstion(), tr("Bill Collection")
            + " (*." + m_lib->getBackendFileExtenstion() + ")");
    }

    saveAs();
}

void MainWindow::on_actionUndo_triggered()
{
    m_lib->undoChange();

    emit uiUpdate();
}

void MainWindow::on_actionRedo_triggered()
{
    m_lib->redoChange();

    emit uiUpdate();
}

void MainWindow::on_actionAdd_Item_triggered()
{
    BillItem billItem;
    BillItemDialog billItemDialog(billItem, this);
    billItemDialog.setCurrencySymbol(m_settingsManager
        ->getMainWindowCurrencySymbol());

    billItemDialog.exec();
    if (billItemDialog.result() == QDialog::Accepted) {
        m_lib->newBillItem(billItemDialog.getBillItem());

        emit uiUpdate();
    }
}

void MainWindow::on_actionEdit_Item_triggered()
{
    // Get the selected bill item reference in the list.
    QList<QTreeWidgetItem *> billItems = itemList->selectedItems();

    if (!billItems.isEmpty()) {
        // Get the bill item
        BillItem selectedBillItem;
        m_lib->getBillItemById(billItems.first()->text(0),
            selectedBillItem);

        // Show the Bill Item Dialog with the information from the selected
        // item.
        BillItemDialog billItemDialog(selectedBillItem, this);
        billItemDialog.exec();

        if (billItemDialog.result() == QDialog::Accepted) {
            // Check if the bill item was modified.
            if (billItemDialog.getBillItem() != selectedBillItem)
            {
                // Update the bill item.
                m_lib->modifyBillItem(
                    billItemDialog.getBillItem());

                // Update the tags and bill items.
                emit uiUpdate();
            }
        }
    }
}

void MainWindow::on_actionDelete_Item_triggered()
{
    // Get the selected bill item reference in the list.
    QList<QTreeWidgetItem *> billItems = itemList->selectedItems();

    if (!billItems.isEmpty()) {
        // Delete the bill item.
        m_lib->deleteBillItem(billItems.first()->text(0));

        emit uiUpdate();
    }
}

void MainWindow::on_actionSearch_triggered()
{
    bool result;

    QString query = QInputDialog::getText(this, tr("Search"), tr("Query"),
        QLineEdit::Normal, m_searchQuery, &result);

    if (result) {
        m_searchQuery = query;
    }

    // if search is selected update the bill items.
    if (!filterList->selectedItems().isEmpty()) {
        if (filterList->selectedItems().at(0)->text(0) == "search") {
            emit billItemsChange();
            return;
        }
    }

    // if search is not selected, select it.
    for (int i = 0; i < filterList->topLevelItemCount(); i++) {
        if (filterList->topLevelItem(i)->text(0) == "search") {
            filterList->topLevelItem(i)->setSelected(true);
            filterList->setCurrentItem(filterList->topLevelItem(i));
            break;
        }
    }
}

void MainWindow::on_actionPreferences_triggered()
{
    SettingsDialog settingsDialog(this);

    settingsDialog.setDuePastColor(m_settingsManager
        ->getMainWindowDuePastColor());
    settingsDialog.setDueTodayColor(m_settingsManager
        ->getMainWindowDueTodayColor());
    settingsDialog.setDueWeekColor(m_settingsManager
        ->getMainWindowDueWeekColor());
    settingsDialog.setCurrencySymbol(m_settingsManager
        ->getMainWindowCurrencySymbol());
    settingsDialog.setBackends(m_lib->getAvaliableBackends(),
        m_lib->getBackendName());

    settingsDialog.exec();
    if (settingsDialog.result() == QDialog::Accepted) {
        m_settingsManager->setMainWindowDuePastColor(settingsDialog
            .getDuePastColor());
        m_settingsManager->setMainWindowDueTodayColor(settingsDialog
            .getDueTodayColor());
        m_settingsManager->setMainWindowDueWeekColor(settingsDialog
            .getDueWeekColor());
        m_settingsManager->setMainWindowCurrencySymbol(settingsDialog
            .getCurrencySymbol());

        if (settingsDialog.getSelectedBackendName()
            != m_lib->getBackendName())
        {
            clearCollectionInformation();

            emit titleUpdate();

            m_lib->setBackend(
                settingsDialog.getSelectedBackendName());
        }

        emit billItemsChange();
    }
}

void MainWindow::on_actionToolbar_triggered()
{
    toolBar->setVisible(actionToolbar->isChecked());
}

void MainWindow::on_actionText_On_Toolbar_triggered()
{
    if (actionText_On_Toolbar->isChecked()) {
        toolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    }
    else {
        toolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
    }
}

void MainWindow::on_actionPlugin_Browser_triggered()
{
    PluginBrowserDialog pluginBrowser(m_pluginManager, this);

    pluginBrowser.exec();
}

void MainWindow::on_actionAbout_triggered()
{
    QString about = "Manage your bills with ease.<br /><br />";
    about += "Copyright (C) 2008 John Schember<br />";
    about += QCoreApplication::applicationName();
    about += " is distributed under the terms of the";
    about += " General Public License (GPL) version 3";

    QFile creditsFile(":/mainwindow/about/credits.html");
    creditsFile.open(QIODevice::ReadOnly);
    QString credits = creditsFile.readAll();
    creditsFile.close();

    QFile licenseFile(":/mainwindow/about/gpl-3.0-standalone.html");
    licenseFile.open(QIODevice::ReadOnly);
    QString license = licenseFile.readAll();
    licenseFile.close();

    AboutDialog aboutDialog(QCoreApplication::applicationName() + " "
        + Constants::Version, about, credits, license, this);

    aboutDialog.exec();
}

void MainWindow::on_actionAbout_Qt_triggered()
{
    QMessageBox::aboutQt(this, "About Qt");
}

void MainWindow::on_filterList_itemSelectionChanged()
{
    emit billItemsChange();
}

void MainWindow::on_tagList_itemSelectionChanged()
{
    emit billItemsChange();
}

void MainWindow::on_itemList_itemSelectionChanged()
{
    actionEdit_Item->setEnabled(!itemList->selectedItems().isEmpty());
    actionDelete_Item->setEnabled(!itemList->selectedItems().isEmpty());

    if (!itemList->selectedItems().isEmpty()) {
        emit billItemSelect(itemList->selectedItems().first());
    }
    else {
        infoPane->clear();
    }
}

void MainWindow::on_itemList_itemActivated()
{
    on_actionEdit_Item_triggered();
}

void MainWindow::uiUpdated()
{
    emit titleUpdate();
    emit tagsChange();
    emit billItemsChange();
    emit undoRedoUpdate();
}

void MainWindow::billItemsChanged()
{
    // Get the id of the selected bill item.
    QString selectedBill = "";
    if (!itemList->selectedItems().isEmpty()) {
        selectedBill = itemList->selectedItems().first()->text(0);
    }
    // We are going to save a reference to the currently selected item later.
    QTreeWidgetItem *selectedItem = 0;

    itemList->clear();

    // Get all selected filters.
    QList<QTreeWidgetItem *> filterItems;
    filterItems = filterList->selectedItems();
    QSet<QString> filters;
    Q_FOREACH (QTreeWidgetItem *filter, filterItems) {
        filters.insert(filter->text(0));
    }

    // Get all selected tags.
    QList<QTreeWidgetItem *> tagItems;
    tagItems = tagList->selectedItems();
    QSet<QString> tags;
    Q_FOREACH (QTreeWidgetItem *tag, tagItems) {
        tags.insert(tag->text(0));
    }

    // Search for the bill items via tags and filters.
    if (filters.contains("all")) {
        m_lib->startGetAllBillItems();
    }
    else if (filters.contains("search")) {
        m_lib->startSearchBillItemsOr(m_searchQuery.split(" ")
            .toSet());
    }
    else if (filters.contains("none")) {
        m_lib->startSearchBillItemsAnd(tags, false,
            true, true, false, true, true, true, false, false, false, false,
            true, true, true, true, false, false, !tags.isEmpty());
    }
    else {
        bool duePast = false;
        bool dueToday = false;
        bool dueFuture = false;

        // Show all due conditions if one are selected. Otherwise no bills
        // will be shown.
        if (!filters.contains("duepast") && !filters.contains("duetoday")
            && !filters.contains("duefuture"))
        {
            duePast = true;
            dueToday = true;
            dueFuture = true;
        }
        // Otherwise use the users choice of due type.
        else {
            if (filters.contains("duepast")) {
                duePast = true;
            }
            if (filters.contains("duetoday")) {
                dueToday = true;
            }
            if (filters.contains("duefuture")) {
                // Today is considered the future since it hasn't past.
                dueToday = true;
                dueFuture = true;
            }
        }

        m_lib->startSearchBillItemsAnd(tags, false,
            (filters.contains("autopay")?true:false),
            (filters.contains("nonautopay")?true:false),
            false, duePast, dueToday, dueFuture,
            false, false, false, false,
            (filters.contains("recurring")?true:false),
            (filters.contains("nonrecurring")?true:false),
            (filters.contains("paid")?true:false),
            (filters.contains("unpaid")?true:false),
            false, false, !tags.isEmpty());
    }

    // Get all the bill items and insert them into the list.
    while (m_lib->hasMoreBillItems()) {
        BillItem billItem;
        QStringList columns;
        // Used to format the amount due to the system locale format
        QLocale locale;

        m_lib->getNextBillItem(billItem);

        columns << billItem.getId() << billItem.getName()
            << m_settingsManager->getMainWindowCurrencySymbol()
                + locale.toString(billItem.getAmountDue())
            << RecurringPeriodType::recurringPeriodTypeToString(
                billItem.getPaymentRecurringPeriod())
            << billItem.getDateDue().toString(Qt::SystemLocaleDate);

        // Insert the bill item and select it if it was selected previously.
        QTreeWidgetItem *insertItem = new QTreeWidgetItem(columns);
        // Set the amount due font to strike though on paid items.
        if (billItem.getPaid()) {
            QFont font = insertItem->font(2);
            font.setStrikeOut(true);
            insertItem->setFont(2, font);
        }
        // Visually show bill status via the due date for unpaid bills.
        else {
            // Only change the font color for bills due after seven days from
            // today.
            if (billItem.getDateDue() <= QDate::currentDate().addDays(7)) {
                // We are going to change the due date for recurring bills
                // and use this modified date for setting the color.
                QDate dueDate = billItem.getDateDue();

                // Recurring bills need to be considered based on their recurring
                // date which changes with the current date. Recurring bills should
                // not be shown as over due.
                switch (billItem.getPaymentRecurringPeriod()) {
                    case RecurringPeriodType::MONTHLY:
                        dueDate = QDate(QDate::currentDate().year(),
                            QDate::currentDate().month(),
                            billItem.getDateDue().day());
                        while (!dueDate.isValid()) {
                            dueDate = dueDate.addDays(-1);
                        }
                        break;
                    case RecurringPeriodType::LASTDAYOFMONTH:
                        dueDate = QDate(QDate::currentDate().year(),
                            QDate::currentDate().month() + 1, 1);
                        dueDate = dueDate.addDays(-1);
                        break;
                    case RecurringPeriodType::YEARLY:
                        dueDate = QDate(QDate::currentDate().year(),
                            billItem.getDateDue().month(),
                            billItem.getDateDue().day());
                        break;
                    case RecurringPeriodType::NONE:
                        break;
                    default:
                        break;
                }

                QBrush brush = insertItem->foreground(4);
                brush.setStyle(Qt::SolidPattern);

                // Set the text color for over due bills.
                // Recurring bills are never considered over due.
                if (dueDate < QDate::currentDate()
                    && billItem.getPaymentRecurringPeriod()
                    == RecurringPeriodType::NONE)
                {
                    brush.setColor(m_settingsManager
                        ->getMainWindowDuePastColor());
                }
                // Set the text color for bills due today.
                else if (dueDate == QDate::currentDate()) {
                    brush.setColor(m_settingsManager
                        ->getMainWindowDueTodayColor());
                }
                // Set the text color for bills due in the next week.
                else if (dueDate > QDate::currentDate()
                    && dueDate <= QDate::currentDate().addDays(7))
                {
                    brush.setColor(m_settingsManager
                        ->getMainWindowDueWeekColor());
                }

                insertItem->setForeground(4, brush);
            }
        }

        itemList->insertTopLevelItem(0, insertItem);
        // Set a reference to the previously selected item if it is still in
        // the list.
        if (billItem.getId() == selectedBill) {
            selectedItem = insertItem;
        }
    }

    // Sort the items in alphabetical order via the last column used to sort.
    int sortColumn = itemList->sortColumn();
    if (sortColumn == 0) {
        sortColumn = 1;
    }
    // Sort by the sort column in the direction it is set to sort by.
    itemList->sortItems(sortColumn, itemList->header()->sortIndicatorOrder());

    // Select the previously selected item.
    if (selectedItem) {
        // We are selecting the item here instead of in the insert because
        // of a bug where selecting it in the insert
        // "if (billItem.getId() == selectedBill)" would stop the insert
        // process. This should be moved back there and saving the reference
        // removed if that can be fixed.
        selectedItem->setSelected(true);
        itemList->setCurrentItem(selectedItem);
    }
    // Select the first item if nothing is currently selected.
    else if (itemList->selectedItems().isEmpty()
        && itemList->topLevelItemCount() > 0)
    {
        itemList->topLevelItem(0)->setSelected(true);
        itemList->setCurrentItem(itemList->topLevelItem(0));
    }
}

void MainWindow::billItemSelected(QTreeWidgetItem *selectedItem)
{
    BillItem billItem;

    m_lib->getBillItemById(selectedItem->text(0), billItem);

    QFile infoPaneFile(":/mainwindow/html/infopane.html");
    infoPaneFile.open(QIODevice::ReadOnly);
    QString infoPaneString = infoPaneFile.readAll();
    infoPaneFile.close();

    infoPaneString.replace("%name%", billItem.getName());
    infoPaneString.replace("%date%", billItem.getDateDue().toString
        ("MMMM dd, yyyy"));
    infoPaneString.replace("%payee%", billItem.getPayee());
    infoPaneString.replace("%paid%", billItem.getPaid()?"Yes":"No");
    infoPaneString.replace("%paymentlocation%", billItem.getPaymentLocation());
    infoPaneString.replace("%autopay%", billItem.getAutoPay()?"Yes":"No");
    infoPaneString.replace("%paymentmethod%", billItem.getPaymentMethod());
    infoPaneString.replace("%paymentrecurring%",
        RecurringPeriodType::recurringPeriodTypeToString(
        billItem.getPaymentRecurringPeriod()));
    infoPaneString.replace("%notes%", billItem.getNotes());

    QString tags = "";
    Q_FOREACH (QString tag, billItem.getTags()) {
        tags += " " + tag;
    }
    infoPaneString.replace("%tags%", tags);

    infoPane->setHtml(infoPaneString);
}

void MainWindow::tagsChanged()
{
    QSet<QString> tags;
    QList<QTreeWidgetItem *> tagItemsSelected;
    QSet<QString> selectedTags;

    // Get all tags.
    tags = m_lib->getAllTags();
    // Get all selected tags.
    tagItemsSelected = tagList->selectedItems();

    // Put the selected tags into a list.
    Q_FOREACH (QTreeWidgetItem *tag, tagItemsSelected) {
        selectedTags.insert(tag->text(0));
    }

    // Clear the tags on the screen.
    tagList->clear();

    Q_FOREACH (QString tag, tags) {
        QStringList columns;
        QString tagDisplayName;

        if (tag == "") {
            tagDisplayName = "(Untagged)";
        }
        else {
            tagDisplayName = tag;
        }

        columns << tag
            << tagDisplayName;

        // Create a new tag item and add to the tag list on screen.
        QTreeWidgetItem *tagItem = new QTreeWidgetItem(columns);
        tagList->insertTopLevelItem(0, tagItem);
        // Check if the added tag was previously selected. If so, select it.
        if (selectedTags.contains(tag)) {
            tagItem->setSelected(true);
        }
    }

    // Sort the tags alphabetically.
    tagList->sortItems(0, Qt::AscendingOrder);
}

void MainWindow::undoRedoUpdated()
{
    actionUndo->setEnabled(m_lib->canUndoChange());
    actionRedo->setEnabled(m_lib->canRedoChange());
}

void MainWindow::titleUpdated()
{
    QString title = QCoreApplication::applicationName();

    if (!m_collectionLocation.isEmpty()) {
        title += " - " + QFileInfo(m_collectionLocation).fileName();
        if (m_lib->shouldSave()) {
            title += " [modified]";
        }
    }

    setWindowTitle(title);
}

void MainWindow::connectSignals()
{
    connect(this, SIGNAL(uiUpdate()), this, SLOT(uiUpdated()));
    connect(this, SIGNAL(billItemsChange()), this, SLOT(billItemsChanged()));
    connect(this, SIGNAL(tagsChange()), this, SLOT(tagsChanged()));
    connect(this, SIGNAL(undoRedoUpdate()), this, SLOT(undoRedoUpdated()));
    connect(this, SIGNAL(billItemSelect(QTreeWidgetItem*)), this,
        SLOT(billItemSelected(QTreeWidgetItem*)));
    connect(this, SIGNAL(titleUpdate()), this, SLOT(titleUpdated()));
}

void MainWindow::clearCollectionInformation()
{
    m_collectionLocation = "";
    m_collectionUsername = "";
    m_collectionLoginname = "";
    m_collectionPassword = "";
}

void MainWindow::save()
{
    // If there is no location then saving cannot be done.
    if (m_collectionLocation.trimmed() != "") {
        if (m_lib->saveCollection(m_collectionLocation,
            m_collectionUsername, m_collectionLoginname, m_collectionPassword))
        {
            emit titleUpdate();
        }
        else {
            QMessageBox::critical(this, tr("Error Saving"),
                m_lib->getLastErrorMessage());
        }
    }
}

void MainWindow::saveAs()
{
    // If there is no location then saving cannot be done.
    if (m_collectionLocation.trimmed() != "") {
        if (m_lib->saveAsCollection(m_collectionLocation,
            m_collectionUsername, m_collectionLoginname, m_collectionPassword))
        {
            emit titleUpdate();
        }
        else {
            QMessageBox::critical(this, tr("Error Saving"),
                m_lib->getLastErrorMessage());
        }
    }
}

bool MainWindow::checkSaveAndShouldContinueAction()
{
    if (m_lib->shouldSave()) {
        int returnCode;

        returnCode = QMessageBox::question(this,
            tr("Collection has been modified"),
            tr("Do you want to save your changes or discard them?"),
            QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel,
            QMessageBox::Save);

        if (returnCode != QMessageBox::Discard) {
            if (returnCode == QMessageBox::Save) {
                on_actionSave_triggered();
            }
            if (m_collectionLocation == ""
                || returnCode == QMessageBox::Cancel)
            {
                return false;
            }
        }
    }

    return true;
}

void MainWindow::loadSettings()
{

    move(m_settingsManager->getMainWindowPosition());
    resize(m_settingsManager->getMainWindowSize());
    restoreState(m_settingsManager->getMainWindowState());

    bool isToolbarVisible = m_settingsManager->isMainWindowToolbarVisible();
    toolBar->setVisible(isToolbarVisible);
    // The window hasn't been shown so we cannot set the visibility using
    // toolBar->isVisible().
    actionToolbar->setChecked(isToolbarVisible);
    toolBar->setToolButtonStyle(m_settingsManager
        ->getMainWindowToolbarButtonStyle());

    HSplitter->restoreState(m_settingsManager->getMainWindowHSplitterState());
    VSplitter->restoreState(m_settingsManager->getMainWindowVSplitterState());

    itemList->header()->restoreState(m_settingsManager
        ->getMainWindowItemListHeaderState());

    QString defaultBackend = m_lib->getBackendName();
    QString savedBackend = m_settingsManager->getBackendCurrent();
    if (!savedBackend.isEmpty() && !m_lib->setBackend(savedBackend)) {
        m_lib->setBackend(defaultBackend);
    }

    Q_FOREACH (QString pluginName, m_settingsManager->getPluginsEnabled()) {
        if (m_pluginManager->getPlugin(pluginName)) {
            m_pluginManager->enablePlugin(pluginName);
        }
    }
}

void MainWindow::saveSettings()
{
    m_settingsManager->setMainWindowPosition(pos());
    m_settingsManager->setMainWindowSize(size());
    m_settingsManager->setMainWindowState(saveState());
    m_settingsManager->setMainWindowToolbarVisible(toolBar->isVisible());
    m_settingsManager->setMainWindowToolbarButtonStyle(toolBar
        ->toolButtonStyle());
    m_settingsManager->setMainWindowHSplitterState(HSplitter->saveState());
    m_settingsManager->setMainWindowVSplitterState(VSplitter->saveState());
    m_settingsManager->setMainWindowItemlistHeaderState(itemList->header()
        ->saveState());
    m_settingsManager->setBackendCurrent(m_lib->getBackendName());
    m_settingsManager->setPluginsEnabled(m_pluginManager->getEnabledPlugins());
}
